package edu.bnu.likun;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

//import sun.org.mozilla.javascript.internal.json.JsonParser;

/**
 * ����
 * �ӿ�   
 */
@WebServlet(name="pay",urlPatterns="/topay")
public class QueryPay extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryPay() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		request.setCharacterEncoding("gbk");
//		response.setContentType("application/json;charSet=GBK");text/plain
		String driverName = getServletContext().getInitParameter("driver");
		String dbURL = getServletContext().getInitParameter("url"); //1433�����ݿ�Ķ˿ڣ�"li"��������ݿ�����
		String userName = getServletContext().getInitParameter("username"); //sa�����ݿ�ĳ����û�����ò�Ҫ��������֣�Ȩ������
		String userPwd = getServletContext().getInitParameter("password"); //sa������  
		response.setContentType("text/plain;charSet=gbk");
		
		
		String str1=request.getParameter("xgh");
		byte[] bytes=str1.getBytes("ISO-8859-1");
		String xgh=new String(bytes,"utf-8");
		
		String str2=request.getParameter("carid");
		String cardid = URLDecoder.decode(str2,"utf-8");
		bytes=cardid.getBytes("ISO-8859-1");
		String carid=new String(bytes,"utf-8");
		
		String str3=request.getParameter("rmb");
		bytes=str3.getBytes("ISO-8859-1");
		String rmb=new String(bytes,"utf-8");
		
		String str4=request.getParameter("date");
		bytes=str4.getBytes("ISO-8859-1");
		String datestr=new String(bytes,"utf-8");
		
		String str5=request.getParameter("number");
		if(str5!=null)bytes=str5.getBytes("ISO-8859-1");
		String number=new String(bytes,"utf-8");
		
		String str6=request.getParameter("way");
		bytes=str6.getBytes("ISO-8859-1");
		
//		String uft8dec=URLDecoder.decode(str6,"UTF-8");
//		String gbkdec=URLDecoder.decode(str6,"GBK");
//		String uft16dec=URLDecoder.decode(str6,"UTF-16");
//		String isodec=URLDecoder.decode(str6,"ISO-8859-1");
//		String gb180dec=URLDecoder.decode(str6,"GB18030");
//		String gb23dec=URLDecoder.decode(str6,"GB2312");
//		
//		System.out.println("**decode֮��utf-8���룺");
//		
//		System.out.println("utf-8 decode��"+new String(uft8dec.getBytes("ISO-8859-1"),"utf-8"));
//		System.out.println("GBK  decode��"+new String(gbkdec.getBytes("ISO-8859-1"),"utf-8"));
//		System.out.println("UTF-16  decode��"+new String(uft16dec.getBytes("ISO-8859-1"),"utf-8"));
//		System.out.println("ISO-8859-1  decode��"+new String(isodec.getBytes("ISO-8859-1"),"utf-8"));
//		System.out.println("GB18030�� decode"+new String(gb180dec.getBytes("ISO-8859-1"),"utf-8"));
//		System.out.println("GB2312�� decode"+new String(gb23dec.getBytes("ISO-8859-1"),"utf-8"));
//		
//        System.out.println("**decode֮��gbk���룺");
//		System.out.println("utf-8 decode��"+new String(uft8dec.getBytes("ISO-8859-1"),"gbk"));
//		System.out.println("GBK  decode��"+new String(gbkdec.getBytes("ISO-8859-1"),"gbk"));
//		System.out.println("UTF-16  decode��"+new String(uft16dec.getBytes("ISO-8859-1"),"gbk"));
//		System.out.println("ISO-8859-1  decode��"+new String(isodec.getBytes("ISO-8859-1"),"gbk"));
//		System.out.println("GB18030�� decode"+new String(gb180dec.getBytes("ISO-8859-1"),"gbk"));
//		System.out.println("GB2312�� decode"+new String(gb23dec.getBytes("ISO-8859-1"),"gbk"));
		
		 System.out.println("**������");
		String str6way="";
		if(str6!=null)
			{
			str6way= URLDecoder.decode(str6,"utf-8");
			bytes=str6.getBytes("ISO-8859-1");
			byte[] bytestest=str6way.getBytes();
			String test=new String(bytestest);
			System.out.println("test:"+test);
			}
		String way=new String(bytes,"utf-8");
		
		Timestamp date=strToDate(datestr);
		System.out.println(str6+":"+str2);
		System.out.println(cardid+":"+str6way);
		System.out.println(way+carid);
		Connection dbConn=null;
		try {
		  Class.forName(driverName).newInstance();
		  dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
		  
		  Statement stmt=dbConn.createStatement();
		  
		  dbConn.setAutoCommit(false);

		  String insertStr="insert into u_pay(xgh,carid,rmb,date,number,way) values('"+xgh+"','"+carid+"','"+rmb+"','"+date+"','"+number+"','"+way+"')";
		  stmt.execute(insertStr);
		  int default_ykys=12;
		  String n_momc=null;
		  
		  String y_pexm=null;
		  int y_peid=0;
		  
		  String n_qxmc=null;
		  int n_yknm=0;//?
		  String n_ykbh=null;//u_per crbh
		  
		  
		  String Upersql="select pexm,peid from u_per where PEZW='"+xgh+"'";
		  
		  ResultSet rs=stmt.executeQuery(Upersql);
		  if(rs.next()){
			  n_qxmc=rs.getString(1);
			  y_peid=rs.getInt(2);
		  }
		  
		  String hrq = "select momc,hrq from u_yksf where peid='" + y_peid + "' and ykcp='"+carid+"' order by hrq desc";
          ResultSet rshrq=stmt.executeQuery(hrq);
          Timestamp hrqq = null;
				  if(rshrq.next()){
					  hrqq=rshrq.getTimestamp("hrq");
					  n_momc=rshrq.getString("momc");
				  }
		  if(hrqq!=null){
			  if(hrqq.getTime()>date.getTime()){
				   date=hrqq;
				}
//		       if(hrqq.getTime()-date.getTime()<1000*60*60*24*90&&hrqq.getTime()-date.getTime()>0){
//		    	   DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
//		           String dateStr = sdf.format(hrqq);   
//		           date=strToDate(dateStr);
//		       }
			 
//		       if(hrqq.getTime()-date.getTime()>1000*60*60*24*90){
//		    	   JsonObject jo=new JsonObject();
//					  jo.addProperty("code", 0);
//					  jo.addProperty("message","离到期时间超过了三个月");
//					  PrintWriter wrter=response.getWriter();
//					  wrter.write(jo.toString());
//					  return;
//		       }
		      
	       }
		  System.out.println("date:"+date);
		  System.out.println("hrqq:"+hrqq);


		  
		  String insertYksf="insert into u_yksf(momc,ykys,hrq,ykje,ykss,yksj,ykbh,yknm,pexm,peid,zffs,ykcp,qxmc) values("
		  		+ "'"+n_momc+"',"+default_ykys+",'"+getEndTime(date)+"',"+rmb+","+rmb+",'"+date+"','"+n_ykbh+"',"+n_yknm+",'"+y_pexm+"',"+y_peid+",'"+way+"','"+carid+"','"+n_qxmc+"')";
				 
		  String updateStr="update u_card set crrqz= '"+getEndTime(date)+"' where PEID=(select PEID from U_PER where PEZW='"+xgh+"') and crcp='"+carid+"'";
		  
		  
		 // String updateStr="update u_yksf set ykje="+rmb+",zffs='"+str6way+"',yksj='"+date+"', hrq= '"+getEndTime(date)+"' where ykcp='"+carid+"'";
		 // String updateStr="update u_yksf set ykje="+rmb+",yksj='"+date+"', hrq= '"+getEndTime(date)+"',zffs='"+way+"' where PEID=(select PEID from U_PER where PEZW='"+xgh+"')";
		 // PEID=(select PEID from U_PER where PEZW='123')
		  
		  stmt.execute(updateStr);
//		  int nn=stmt.executeUpdate(updateStr);
		  int nn=stmt.executeUpdate(insertYksf);
		 // stmt.execute(updteStr);
		  
		  dbConn.commit();
		  
		  JsonObject jo=new JsonObject();
		  jo.addProperty("code", 1);
		  jo.addProperty("rows",nn);
			  	  
		  PrintWriter wrter=response.getWriter();
		  wrter.write(jo.toString());
		  
		  
		}
		catch (Exception e) {
			  //e.printStackTrace();
//			  try {
//				//dbConn.rollback();
//			  } catch (SQLException e1) {
//				// TODO Auto-generated catch block
//				//e1.printStackTrace();
//			 }
			  JsonObject jo=new JsonObject();
			  jo.addProperty("code", 0);
			  jo.addProperty("message", e.getMessage());
			  PrintWriter wrter=response.getWriter();
			  wrter.write(jo.toString());
		 
		}
		finally{
		try {
		   if(dbConn!=null)
		    dbConn.close();
		   }  catch (SQLException e) {
		// TODO Auto-generated catch block
		  e.printStackTrace();
		  }
		  }
		}
		
   private Timestamp getEndTime(Timestamp dtt){
	   java.util.Date date=new java.util.Date();
	   Calendar ca=Calendar.getInstance();
	   ca.setTime(dtt);
	   ca.add(Calendar.YEAR, 1);
	   date=ca.getTime();
	   
	   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
	  String str= format.format(date);
	  java.util.Date dt = null;
	  try {
		dt = format.parse(str);
	    } catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	   }
	   return new Timestamp(dt.getTime());
     }
		
	public  Timestamp strToDate(String str) {
		  
		   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		   java.util.Date date = null;
		   try {
		    date = format.parse(str);
		    
		   } catch (ParseException e) {
		    e.printStackTrace();
		    return null;
		   }
		   return new Timestamp(date.getTime());
		}
	}

	


